/*
 * 创建日期 2010-6-1
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.compile;

import java.util.List;
import java.util.regex.Pattern;

import  org.fantasy.common.util.StringUtil;

/**
 *  Sql解析器
 * @author: 王文成
 * @version: 1.0
 * @since 2010-6-1
 */
public class SqlParser {

    private static final Pattern PATTERN = Pattern.compile("(\\w+)([(]?([,.:\\w]*)[)]?)?");

    private static String RESULT_MAP = " org.fantasy.common.util.ResultMap rm = new  org.fantasy.common.util.ResultMap(map);\n";

    private String sql;

    public SqlParser(String sql) {
        this.sql = sql;
    }

    /**
     * 解析
     * 
     * @return
     */
    public String parse() {
        this.addSqlCommon();
        this.parseSql();
        return sql;
    }

    /**
     * 添加SQLCommon
     * 
     * @return
     */
    public void addSqlCommon() {
        if (!sql.contains("ResultMap")) {
            String comm = RESULT_MAP;
            sql = comm + sql;
        }
    }

    /**
     * SQL解析
     * 
     * @return
     */
    public void parseSql() {
        List<String> params = StringUtil.matchs(sql, "#(\\w+)#", 1);
        for (String param : params) {
            String key = param.trim();
            sql = sql.replace("#" + param + "#", "\" + rm.getString(\"" + key + "\") + \"");
        }
    }

    public static void main(String[] args) {
        StringBuffer sql = new StringBuffer();
        sql.append("   AND @RegionIdIn(A.REGION_ID)@ \n");
        sql.append("   AND @RegionIdIn(D.REGION_ID)@ \n");
        sql.append("   AND @RegionIdIn(E.REGION_ID)@ \n");
        sql.append("   AND @RegionIdIn(F.REGION_ID)@ \n");
        sql.append("   AND @BssOrgIdIn(E.BSS_ORG_ID,:bssOrgId)@\n");
        List<String> values = StringUtil.matchs(sql.toString(), "@(.+)@", 1);
        for (String value : values) {
            // System.out.println(value);
        }
        String s1 = "RegionIdIn()";
        String s2 = PATTERN.matcher(s1).replaceAll("$3");
        System.out.println(s2);
        String s3 = "   AND @BssOrgIdIn(E.BSS_ORG_ID,:bssOrgId)@";
        System.out.println(s3.replace("(E.BSS_ORG_ID,:bssOrgId)", ""));
    }
}
